package org.september.pisces.operation.controller;

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;

import org.apache.catalina.startup.Tomcat;
import org.september.simpleweb.auth.PublicMethod;
import org.september.simpleweb.model.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@RestController
@RequestMapping("/pisces/operation")
public class StatusController {
	
	@Autowired
	private ServletWebServerApplicationContext applicationContext;
	
    
    @ResponseBody
    @RequestMapping(value = "/systemStatus")
    public ModelAndView systemStatus() {
    	ModelAndView mv = new ModelAndView();
//    	long freeSpace = path.getFreeSpace()/1024/1024/1024;//G
//    	long totalSpace = path.getTotalSpace()/1024/1024/1024;
    	mv.addObject("freeSpace", "");
    	mv.addObject("totalSpace", "");
    	
    	Runtime runtime = Runtime.getRuntime();
        long totalMemory = runtime.totalMemory()/1024/1024; // 总内存大小
        long freeMemory = runtime.freeMemory()/1024/1024; // 已分配内存大小
        long usedMemory = totalMemory - freeMemory;
        mv.addObject("totalMemory", totalMemory);
        mv.addObject("freeMemory", freeMemory);
        mv.addObject("usedMemory", usedMemory);
        
        OperatingSystemMXBean osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        String osJson = JSON.toJSONString(osBean,true);
        JSONObject json = JSON.parseObject(osJson);
        mv.addObject("freePhysicalMemorySize", json.getDouble("freePhysicalMemorySize")/1024/1024/1024);
        mv.addObject("systemCpuLoad", json.getDouble("systemCpuLoad")*100);
        mv.addObject("processCpuLoad", json.getDouble("processCpuLoad")*100);
        mv.addObject("osJson", osJson);
        
        mv.addObject("lastBootTime", "");
    	return mv;
    }
	
	@RequestMapping("/all")
	@ResponseBody
    @PublicMethod
    public ResponseVo<String> all() {
		Tomcat tomcat = ((TomcatWebServer) applicationContext.getWebServer()).getTomcat();
		String tomcatLog = tomcat.getConnector().getProtocolHandler().getExecutor().toString();
		return ResponseVo.<String>BUILDER().setData(tomcatLog).setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
    }
}
